import * as Models from '@/models'

// 验证必填字段
export function validateRequired(data, fields) {
  const errors = []
  fields.forEach(field => {
    if (!data[field] && data[field] !== 0) {
      errors.push(`${field}不能为空`)
    }
  })
  return errors
}

// 验证字符串长度
export function validateLength(value, field, min, max) {
  if (value.length < min || value.length > max) {
    return `${field}长度必须在${min}-${max}个字符之间`
  }
  return null
}

// 验证邮箱格式
export function validateEmail(email) {
  const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!re.test(email)) {
    return '邮箱格式不正确'
  }
  return null
}

// 验证文件大小
export function validateFileSize(size, maxSize) {
  if (size > maxSize) {
    return `文件大小不能超过${maxSize / 1024 / 1024}MB`
  }
  return null
}

// 验证文件类型
export function validateFileType(type, allowedTypes) {
  if (!allowedTypes.includes(type)) {
    return `不支持的文件类型：${type}`
  }
  return null
}

// 验证价格
export function validatePrice(price) {
  if (price < 0) {
    return '价格不能为负数'
  }
  return null
}

// 验证日期
export function validateDate(date) {
  if (isNaN(Date.parse(date))) {
    return '日期格式不正确'
  }
  return null
}

// 验证模型数据
export function validateModel(data, modelName) {
  const model = Models[modelName]
  if (!model) {
    throw new Error(`未找到模型：${modelName}`)
  }

  const errors = []
  Object.keys(model).forEach(key => {
    const value = data[key]
    const modelValue = model[key]

    // 验证类型
    if (typeof value !== typeof modelValue) {
      errors.push(`${key}类型不正确，应为${typeof modelValue}`)
    }

    // 验证必填字段
    if (value === undefined || value === null) {
      errors.push(`${key}不能为空`)
    }

    // 验证特定字段
    switch (key) {
      case 'email':
        const emailError = validateEmail(value)
        if (emailError) errors.push(emailError)
        break
      case 'price':
        const priceError = validatePrice(value)
        if (priceError) errors.push(priceError)
        break
      case 'createTime':
      case 'updateTime':
      case 'expireTime':
        const dateError = validateDate(value)
        if (dateError) errors.push(dateError)
        break
    }
  })

  return errors
}

// 数据转换函数
export function transformData(data, modelName) {
  const model = Models[modelName]
  if (!model) {
    throw new Error(`未找到模型：${modelName}`)
  }

  const result = {}
  Object.keys(model).forEach(key => {
    const value = data[key]
    const modelValue = model[key]

    // 类型转换
    switch (typeof modelValue) {
      case 'number':
        result[key] = Number(value)
        break
      case 'boolean':
        result[key] = Boolean(value)
        break
      case 'string':
        result[key] = String(value)
        break
      case 'object':
        if (Array.isArray(modelValue)) {
          result[key] = Array.isArray(value) ? value : []
        } else {
          result[key] = value || {}
        }
        break
      default:
        result[key] = value
    }
  })

  return result
} 